package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.FoodCategory;
import com.myapp.ruyixing.model.FoodCategory.FoodCategoryItem;

public class FoodTypeFragment extends ListFragment implements
		OnItemClickListener {

	private FoodCategory mFoodCategory;

	public static FoodTypeFragment newOrderMenuFragment(boolean showPrice) {
		FoodTypeFragment fragment = new FoodTypeFragment();
		Bundle bundle = new Bundle();
		bundle.putBoolean("showPrice", showPrice);
		fragment.setArguments(bundle);

		return fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		RYHttpClient.getFoodCategory(getActivity(),
				new RYHttpResponseHandler() {

					@Override
					public void onSuccess(Object o) {
						FoodCategory data = (FoodCategory) o;
						mFoodCategory = data;
						if (data != null && data.data != null) {
							setListAdapter(new ArrayAdapter<String>(
									getActivity(),
									android.R.layout.simple_list_item_1,
									getNameList()));
							getListView().setOnItemClickListener(
									FoodTypeFragment.this);
						}
					}

					@Override
					public void onFailure(Throwable throwable) {
						if (getActivity() != null && isAdded() && isVisible()) {
							Toast.makeText(getActivity(), "加载美食种类失败",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String name = (String) ((BaseAdapter) parent.getAdapter())
				.getItem(position);
		String typeid = getItemId(name);

		((FoodListActivity) getActivity()).changeType(typeid, name);
	}

	private String[] getNameList() {
		List<String> names = new ArrayList<String>();
		for (FoodCategoryItem item : mFoodCategory.data) {
			names.add(item.name);
		}

		return names.toArray(new String[0]);
	}

	private String getItemId(String name) {
		for (FoodCategoryItem item : mFoodCategory.data) {
			if (name.equals(item.name)) {
				return item.id;
			}
		}

		return null;
	}
}
